package com.yksj.healthtalk.ui.dictionary;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.ui.R;

/**
 * 医院地图列表
 * @author zhao
 *
 */
public class DictionaryMapListFragment extends Fragment implements OnClickListener {
	MapView mapView;
	MapController mapController;
	
	String mType;
	//分类赛选
	Map<String,JSONArray> mTypeMap;
	MItemizedOverlay mOverlay;
	final Map<String,List<OverlayItem>> mOverlayMap = new HashMap<String, List<OverlayItem>>();
	String mCurrentKeyType;//当前类型
	PopupOverlay mPopupOverlay;
	private OverlayItem mCurItem = null;
	private View mPopItmView;
	private TextView mPopTextView;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mType = getArguments().getString("type");
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.dictionary_map_list_layout,null);
		Button button = (Button)view.findViewById(R.id.dictionary_filter1);
		mapView = (MapView)view.findViewById(R.id.bmapsView);
		button.setText("10015".equals(mType) ? "医院类型" : "药店类型");
		registerForContextMenu(button);
		button.setOnClickListener(this);
		mapController = mapView.getController();
		mapController.enableClick(true);
		mapController.setZoom(14);
		mapView.setBuiltInZoomControls(false);
		
		mOverlay = new MItemizedOverlay(getResources().getDrawable(R.drawable.icon_marka), mapView);
		mapView.getOverlays().add(mOverlay);
		
		mPopItmView = inflater.inflate(R.layout.map_overlay_item_layout,null);
		mPopTextView = (TextView)mPopItmView.findViewById(R.id.textcache);
		
		//item 泡泡点击
		PopupClickListener popListener = new PopupClickListener() {
			@Override
			public void onClickedPopup(int index) {
				String title = mCurItem.getTitle();
				String code = mCurItem.getSnippet();
				queryContent(title, code);
			}
		};
		mPopupOverlay = new PopupOverlay(mapView,popListener);
		return view;
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if("10015".equals(mType)){//附近就医,等级赛选
			menu.setHeaderTitle("选择等级");
			for (String key : mTypeMap.keySet()) {
				menu.add(key);
			} 
		}else if("10016".equals(mType)){//附近药店,类型赛选
			for (String key : mTypeMap.keySet()) {
				menu.add(key);
			} 
		}	
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		String name = item.toString();
		if(!name.equals(mCurrentKeyType)){
			onChangeOverLay(name);
		}
		return super.onContextItemSelected(item);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if(mTypeMap == null){
			String content = getArguments().getString("parame");
			try{
				JSONTokener jsonTokener = new JSONTokener(content);
				Object object = jsonTokener.nextValue();
				if(object instanceof JSONArray){
					onDataTypeSort((JSONArray)object);
				}else if(object instanceof JSONObject){
					JSONArray jsonArray = ((JSONObject)object).getJSONArray("data");
					onDataTypeSort(jsonArray);
				}
			}catch(JSONException e){
				e.printStackTrace();
			}
		}
		
		onChangeOverLay(mCurrentKeyType);
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.dictionary_filter1:
			v.showContextMenu();
			break;
		}
	}
	
	private void onChangeOverLay(String type){
		mOverlay.removeAll();
		if(type == null)type = getString(R.string.limit_no);
		if(mOverlayMap.containsKey(type)){//缓存获取
			List<OverlayItem> items = mOverlayMap.get(type);
			mOverlay.addItem(items);
			return;
		}else{
			JSONArray array = mTypeMap.get(type);
			if(array == null)return;
			List<OverlayItem> listItems = new ArrayList<OverlayItem>();
			Drawable drawable = getResources().getDrawable(R.drawable.icon_marka);
			for (int i = 0; i < array.length(); i++) {
				try {
					JSONObject jsonObject = array.getJSONObject(i);
					double lat = jsonObject.getDouble("LATITUDE");
					double lont = jsonObject.getDouble("LONGITUDE");
					String title = jsonObject.optString("NAME","");
					String code = jsonObject.optString("CODE","");
					
					GeoPoint point = new GeoPoint((int)(lat*1E6),(int)(lont*1E6));
					OverlayItem item = new OverlayItem(point,title,code);
					item.setMarker(drawable);
					listItems.add(item);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			mOverlayMap.put(type,listItems);
			mOverlay.addItem(listItems);
		}
		mCurrentKeyType = type;
		if(mPopupOverlay != null){
			mPopupOverlay.hidePop();
		}
		mapView.refresh();
	}
	
	/**
	 * 
	 * 对数据进行分类
	 * @param jsonArray
	 */
	private void onDataTypeSort(JSONArray jsonArray){
		mTypeMap = new LinkedHashMap<String, JSONArray>();
		mTypeMap.put(getString(R.string.limit_no),jsonArray);
		for (int i = 0; i < jsonArray.length(); i++) {
			try {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				String type = null;
				
				if(jsonObject.has("LEVEL_NAME")){
					type = jsonObject.getString("LEVEL_NAME");
				}else if(jsonObject.has("TYPE")){
					type = jsonObject.getString("TYPE");
				}
				boolean isContain = mTypeMap.containsKey(type);
				JSONArray array;
				if(isContain){
					array = mTypeMap.get(type);
				}else{
					array = new JSONArray();
					mTypeMap.put(type, array);
				}
				array.put(jsonObject);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 查询具体内容
	 * @param title
	 * @param code
	 */
	private void queryContent(String title,String code){
		if("10015".equals(mType)){//附近就医
			HttpRestClient.doHttpSeeDoctorServlet(null, null, null, null, null, code, null, new MHttpResponseHandler(title,code));
		}else{
			HttpRestClient.doHttpSeeDoctorServlet(null, null, null, null, null, code, null, new MHttpResponseHandler(title,code));
		}
	}
	
	private class MHttpResponseHandler extends AsyncHttpResponseHandler{
		private String mTitleName;
		private String mCode;
		public MHttpResponseHandler(String name,String code) {
			this.mTitleName = name;
			this.mCode = code;
		}
		public void onSuccess(int statusCode, String content) {
			super.onSuccess(statusCode, content);
			if(!isDetached()){
				Intent intent = new Intent(getActivity(),DictionaryContentActivity.class);
				intent.putExtra("result",content);
				intent.putExtra("title",mTitleName);
				startActivityForResult(intent,1);	
			}
		};
	}
	
	/**
	 * 从view 得到图片
	 * @param view
	 * @return
	 */
	private  Bitmap getBitmapFromView(View view) {
        view.destroyDrawingCache();
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = view.getDrawingCache(true);
        return bitmap;
	}
	
	public class MItemizedOverlay extends ItemizedOverlay{
		public MItemizedOverlay(Drawable arg0, MapView arg1) {
			super(arg0, arg1);
		}
		@Override
		protected boolean onTap(int index) {
			OverlayItem item = getItem(index);
			mCurItem = item;
			String title = item.getTitle();
			mPopTextView.setText(title);
			Bitmap[] bitmaps = {getBitmapFromView(mPopItmView)};
			mPopupOverlay.showPopup(bitmaps,item.getPoint(), 32);
			return true;
		}
		
		/**
		 * 响应点击事件
		 */
		@Override
		public boolean onTap(GeoPoint arg0, MapView arg1) {
			if(mPopupOverlay != null){
				mPopupOverlay.hidePop();
			}
			return false;
		}
	}
	
}
